from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from users.models import User


class CustomBackend(ModelBackend):
    """用户登录验证功能"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # noinspection PyBroadException
        try:
            # 添加了一个手机验证，如果需要其他验证再加
            user = User.objects.get(Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class FormulaTokenObtainPairSerializer(TokenObtainPairSerializer):
    """自定义 token内容 和返回数据格式 序列化"""

    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass

    # token的中间可解码段信息 需要增加信息 重写 get_token(cls,user): 方法
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        # 增加想要加到token中的信息 默认只有user.id
        token['username'] = user.username
        token['email'] = user.email
        # ...
        return token

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        data['username'] = self.user.username
        data['mobile'] = self.user.mobile
        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)

        return {"code": "200", "msg": "ok", "data": data}


class FormulaTokenObtainPairView(TokenObtainPairView):
    """登录认证后 获取token视图"""
    serializer_class = FormulaTokenObtainPairSerializer
